$(document).ready(function () {
  // 图片查看器功能
  const imageViewer = $(
    '<div class="image-viewer"><img src="" alt="大图"></div>',
  ).appendTo('body');

  $('.gallery-image').click(function () {
    const imgSrc = $(this).attr('src');
    imageViewer.find('img').attr('src', imgSrc);
    imageViewer.addClass('active');
  });

  imageViewer.click(function () {
    $(this).removeClass('active');
  });

  // 美食分类筛选
  $('.category-btn').click(function () {
    const category = $(this).data('category');

    // 更新按钮状态
    $('.category-btn').removeClass('active');
    $(this).addClass('active');

    // 筛选文章
    if (category === 'all') {
      $('.post-item').show();
    } else {
      $('.post-item').each(function () {
        if ($(this).data('category') === category) {
          $(this).show();
        } else {
          $(this).hide();
        }
      });
    }
  });

  // 搜索功能
  $('#search-btn').click(function () {
    const searchText = $('#search-input').val().toLowerCase();
    $('.post-item').each(function () {
      const postContent = $(this).text().toLowerCase();
      if (postContent.includes(searchText)) {
        $(this).show();
      } else {
        $(this).hide();
      }
    });
  });

  // 回车触发搜索
  $('#search-input').keypress(function (e) {
    if (e.which === 13) {
      $('#search-btn').click();
    }
  });

  // 评论功能
  $('#commentForm').submit(function (e) {
    e.preventDefault();
    const name = $('#commenterName').val();
    const content = $('#commentContent').val();
    const date = new Date().toLocaleDateString();

    // 创建新评论
    const newComment = $(`
            <li class="comment">
                <div class="comment-header">
                    <span class="commenter-name">${name}</span>
                    <span class="comment-date">${date}</span>
                </div>
                <div class="comment-content">${content}</div>
            </li>
        `);

    // 添加到评论列表
    $('.comment-list').prepend(newComment);

    // 保存到localStorage
    const comments = JSON.parse(localStorage.getItem('foodComments') || '[]');
    comments.unshift({ name, content, date });
    localStorage.setItem('foodComments', JSON.stringify(comments));

    // 清空表单
    this.reset();
  });

  // 加载已有评论
  function loadComments() {
    const comments = JSON.parse(localStorage.getItem('foodComments') || '[]');
    const commentList = $('.comment-list');
    commentList.empty();

    comments.forEach((comment) => {
      const commentElement = $(`
                <li class="comment">
                    <div class="comment-header">
                        <span class="commenter-name">${comment.name}</span>
                        <span class="comment-date">${comment.date}</span>
                    </div>
                    <div class="comment-content">${comment.content}</div>
                </li>
            `);
      commentList.append(commentElement);
    });
  }

  loadComments();

  // 图片懒加载
  const lazyImages = document.querySelectorAll('.gallery-image');
  const imageObserver = new IntersectionObserver((entries, observer) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        const img = entry.target;
        img.src = img.dataset.src;
        observer.unobserve(img);
      }
    });
  });

  lazyImages.forEach((img) => {
    imageObserver.observe(img);
  });

  // 餐厅评分动画
  function animateRatings() {
    $('.rating-score').each(function () {
      const $this = $(this);
      const score = parseFloat($this.text());
      $({ value: 0 }).animate(
        { value: score },
        {
          duration: 1500,
          step: function () {
            $this.text(this.value.toFixed(1));
          },
        },
      );
    });
  }

  // 当评分区域进入视口时触发动画
  const ratingObserver = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        animateRatings();
        ratingObserver.unobserve(entry.target);
      }
    });
  });

  $('.food-rating').each(function () {
    ratingObserver.observe(this);
  });

  // 美食地图标记提示
  $('.map-pin').each(function () {
    const title = $(this).attr('title');
    const tooltip = $('<div class="tooltip"></div>').text(title);
    $(this).append(tooltip);
  });

  // 热门餐厅点击效果
  $('.restaurant-item').click(function () {
    const name = $(this).find('h4').text();
    const rating = $(this).find('.restaurant-rating').text();
    const info = $(this).find('p').text();
    alert(`${name}\n评分：${rating}\n${info}\n\n点击查看详细信息`);
  });

  // 标签点击筛选
  $('.tag-item').click(function (e) {
    e.preventDefault();
    const tag = $(this).text().toLowerCase();

    // 重置分类按钮状态
    $('.category-btn').removeClass('active');
    $('.category-btn[data-category="all"]').addClass('active');

    $('.post-item').each(function () {
      const postTags = $(this)
        .find('.tag')
        .map(function () {
          return $(this).text().toLowerCase();
        })
        .get();

      if (postTags.includes(tag)) {
        $(this).show();
      } else {
        $(this).hide();
      }
    });
  });
});
